﻿// TLConsole.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "UtilityTool.h"
#include <string>
std::string ReadIniString(const std::string& section, const std::string& key, const std::string& defaultValue, const std::string& filePath) {
    char buffer[256];
    DWORD bufferSize = sizeof(buffer) / sizeof(char);
    GetPrivateProfileStringA(section.c_str(), key.c_str(), defaultValue.c_str(), buffer, bufferSize, filePath.c_str());
    return std::string(buffer);
}

int ReadIniInt(const std::string& section, const std::string& key, int defaultValue, const std::string& filePath) {
    return GetPrivateProfileIntA(section.c_str(), key.c_str(), defaultValue, filePath.c_str());
}

void WriteIniString(const std::string& section, const std::string& key, const std::string& value, const std::string& filePath) {
    WritePrivateProfileStringA(section.c_str(), key.c_str(), value.c_str(), filePath.c_str());
}

void WriteIniInt(const std::string& section, const std::string& key, int value, const std::string& filePath) {
    char buffer[16];
    sprintf_s(buffer, "%d", value);
    WritePrivateProfileStringA(section.c_str(), key.c_str(), buffer, filePath.c_str());
}

std::string url_encode(const std::string& value) {
    std::ostringstream encoded;
    for (unsigned char c : value) {
        // 允许的字符
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            encoded << c;
        }
        else {
            // 将其他字符转换为百分号编码...
            encoded << '%' << std::uppercase << std::setw(2) << std::setfill('0') << static_cast<int>(c);
        }
    }
    return encoded.str();
}

int main(int argc, char* argv[])
{

    //检查全局配置
    std::string filePath = GetExeDirectory() +"\\Settings.ini";
    // 读取数据
    std::string key = ReadIniString("global", "key", "", filePath);
    std::string steamPath = ReadIniString("global", "steamPath", "", filePath);

    if (key.empty())
    {
        std::cout << "请输入卡密(key): ";
        std::cin >> key;
        WriteIniString("global", "key", key, filePath);
    }
    if (steamPath.empty())
    {
        std::cout << "请输入Steam完整路径: ";
        std::cin >> steamPath;
        WriteIniString("global", "steamPath", steamPath, filePath);
    }

    HttpClient h;
    //检查python环境
    std::string python_version = get_python_version();
    spdlog::info("python_version:{}" , python_version);
    if (python_version.empty())
    {
        spdlog::info("没有发现python环境，开始下载安装！");
        std::string pythonstr;
        h.Get("https://mirrors.huaweicloud.com/python/3.12.4/python-3.12.4-amd64.exe" , pythonstr);
        size_t s = pythonstr.size();
        WriteBinaryToFile("python-3.13.0-amd64.exe", pythonstr.c_str(), pythonstr.size());
        std::string command = "python-3.13.0-amd64.exe /passive InstallAllUsers=1 PrependPath=1";
        int result = system(command.c_str());
        if (result == 0) {
            spdlog::info("安装成功，请重启本程序");
        }
        else {
            spdlog::error("安装失败，错误代码：{}", result);
        }
        system("pause");
        return 0;
    }

    //下载DLL
    std::string dllstr;
    h.Get("http://202.189.9.39:8080/TLSteam.dll", dllstr);
   // WriteBinaryToFile("TLSteam.7z", dllstr.c_str(), dllstr.size());
    if (dllstr.empty())
    {
        spdlog::error("fs:下载dll失败");
        system("pause");
        return 0;
    }
    spdlog::info("fs: dll下载成功,大小:{}" , dllstr.size());
    //WriteBinaryToFile("x64.dll", dllstr.c_str(), dllstr.size());

    if (!logninTh(key , dllstr))
    {
        return 0;
    }

    //DeleteFile("TLSteam.7z");
    
    {
        spdlog::info("开始下载脚本");
        //下载脚本
        std::string scriptStr;
        h.Get("https://gitee.com/tl_hujian/steamtl/raw/master/tlScript.zip", scriptStr);
        WriteBinaryToFile("tlScript.zip", scriptStr.c_str(), scriptStr.size());
        auto path = GetExeDirectory() + "\\tlScript.zip";
        std::string command = FormatString(R"(tar -xf "%s" -C "%s")", path.c_str() , GetExeDirectory().c_str());

        int result = system(command.c_str());
        if (result == 0) {
            spdlog::info("脚本解压成功");
            
            command = FormatString(R"(pip install -r %s\tlScript\requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple)", GetExeDirectory().c_str()).c_str();
            spdlog::info("开始安装pip模块 ： {}" , command);
            result = system(command.c_str());
            if (result == 0)
            {
                spdlog::info("pip模块安装成功");
            }
            else
            {
                spdlog::info("pip模块安装失败");
            }

        }
        else {
            spdlog::error("脚本解压失败");
            system("pause");
            return 0;
        }

    }


    while (true)
    {
        {
            // Python 脚本的路径
            std::string script_path = GetExeDirectory() + "\\tlScript\\main.py";

            namespace bp = boost::process;
            // 创建并启动 Python 进程
            bp::child python_process(
                bp::search_path("python"), // 查找 Python 可执行文件
                script_path,               // Python 脚本路径
                bp::std_out > stdout,      // 将标准输出重定向到控制台
                bp::std_err > stderr       // 将标准错误重定向到控制台
            );

            // 等待进程结束
            python_process.wait();
        }

    }

    return 1;
}





